package org.xbdframework.boot.autoconfigure.quartz;

import org.quartz.Scheduler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.xbdframework.scheduling.quartz.QuartzListenerRegister;
import org.xbdframework.scheduling.quartz.QuartzTaskHandler;
import org.xbdframework.scheduling.quartz.handler.DefaultQuartzTaskHandler;

@Configuration
@ConditionalOnClass({ QuartzTaskHandler.class, DefaultQuartzTaskHandler.class })
public class QuartzTaskHandlerConfiguration {

    private final ApplicationContext applicationContext;

    private final Scheduler scheduler;

    public QuartzTaskHandlerConfiguration(ApplicationContext applicationContext,
                                          Scheduler scheduler) {
        this.applicationContext = applicationContext;
        this.scheduler = scheduler;
    }

    @Bean
    @ConditionalOnMissingBean
    public QuartzListenerRegister quartzListenerRegister() {
        QuartzListenerRegister quartzListenerRegister = new QuartzListenerRegister();
        quartzListenerRegister.setApplicationContext(this.applicationContext);
        quartzListenerRegister.setScheduler(this.scheduler);
        return quartzListenerRegister;
    }

    @Bean
    @ConditionalOnMissingBean(QuartzTaskHandler.class)
    public QuartzTaskHandler defaultQuartzTaskHandler() {
        DefaultQuartzTaskHandler defaultQuartzTaskHandler = new DefaultQuartzTaskHandler(
                DefaultXbdQuartzJobBean.class);
        defaultQuartzTaskHandler.setScheduler(scheduler);
        return defaultQuartzTaskHandler;
    }

}
